package com.gl.saasservice.area.service;

import com.gl.framework.web.response.Result;
import com.gl.saasservice.area.entity.Area;
import com.gl.saasservice.area.repository.AreaRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Sort;

import javax.persistence.criteria.Predicate;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class AreaService {
    private static final Logger log = LoggerFactory.getLogger(AreaService.class);

    @Autowired
    private AreaRepository areaRepository;


    @SuppressWarnings("rawtypes")
    public Result list(Long parentId) {
        /**
         * 查询所有地区并按照sortby排序
         */
        try {
            List<Map> data = areaRepository.findAll((root, query, cb) -> {
                List<Predicate> list = new ArrayList<>();
                list.add(cb.equal(root.get("parentId"), parentId));
                return cb.and(list.toArray(new Predicate[list.size()]));
            }, Sort.by(Sort.Direction.ASC, "sortby"))
                    .stream()
                    .map(area -> {
                        Map<String, Object> vo = new HashMap<>(2);
                        vo.put("id", area.getId());
                        vo.put("name", area.getName());
                        return vo;
                    })
                    .collect(Collectors.toList());

            return Result.success(data);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.fail();
        }
    }

    public List<Area> findByIdIn(List<Long> id) {

        return areaRepository.findByIdIn(id);
    }

}
